import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'

export function generaMenu(routes, data, resolve) {
  data.forEach(item => {
    const menu = {
      path: item.outer_link === 1 ? item.url : item.path, // 判断是否为外链形式
      component: item.component === '#' ? Layout : (resolve) => require([`@/views${item.component}`], resolve),
      hidden: item.hidden,
      redirect: item.redirect,
      children: [],
      name: item.name,
      meta: item.meta
    }
    if (item.children) {
      generaMenu(menu.children, item.children, resolve)
    }
    routes.push(menu)
  })
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, {menu}) {
    return new Promise(resolve => {
      let loadMenuData = []
      Object.assign(loadMenuData, menu)
      const tempAsyncRoutes = Object.assign([], asyncRoutes)
      generaMenu(tempAsyncRoutes, loadMenuData, resolve)
      commit('SET_ROUTES', tempAsyncRoutes)
      resolve(tempAsyncRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
